package c15;

/**
 * 集合点
 */
public class AssemblePoint {
    private int n;

    public AssemblePoint(int n) {
        this.n = n;
    }

    public synchronized void await() throws InterruptedException {
        if (n > 0) {
            n--;
            System.out.println(Thread.currentThread().getName() + " arrive");
            if (n == 0) {
                notifyAll();
            } else {
                while (n != 0) {
                    wait();
                }
            }
        }
    }

    // 多个游客线程，使用该协作对象到达集合点进行同步的示例
    static class Tourist extends Thread {
        AssemblePoint ap;

        public Tourist(AssemblePoint ap) {
            this.ap = ap;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                ap.await();
                System.out.println(Thread.currentThread().getName() + " do something");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        AssemblePoint ap = new AssemblePoint(64);
        for (int i = 0; i < 64; i++) {
            Tourist tourist = new Tourist(ap);
            tourist.start();
        }
    }
}
